package com.sky.service.impl;


import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {


    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /*
     *
     * 营业额统计
     *
     * */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {

        //需要获取日期列表dateList
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }


        //需要获取营业额列表turnoverList
        List<Double> turnoverList = new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        turnoverReportVO.setDateList(StringUtils.join(dateList, ","));
        turnoverReportVO.setTurnoverList(StringUtils.join(turnoverList, ","));

        return turnoverReportVO;
    }


    /*
     *
     * 用户统计
     *
     * */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {

        //需要获取日期列表dateList
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        UserReportVO userReportVO = new UserReportVO();
        userReportVO.setDateList(StringUtils.join(dateList, ","));

        //获取用户总量
        List<Double> totalUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime time = LocalDateTime.of(date, LocalTime.MAX);
            Double userCount = userMapper.getUserCount(time);
            totalUserList.add(userCount);
        }
        userReportVO.setTotalUserList(StringUtils.join(totalUserList, ","));


        //获取新增用户数量(用当日用户总量减去昨日用户总量即可)
        List<Double> newUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime todayTime = LocalDateTime.of(date, LocalTime.MAX);
            Double todayUserCount = userMapper.getUserCount(todayTime);

            LocalDateTime yesterdayTime = todayTime.plusDays(-1);
            Double yesterdatUserCount = userMapper.getUserCount(yesterdayTime);

            double newUserCount = todayUserCount - yesterdatUserCount;

            newUserList.add(newUserCount);
        }
        userReportVO.setNewUserList(StringUtils.join(newUserList, ","));

        return userReportVO;
    }


    /*
     *
     * 订单统计
     *
     * */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {

        //需要获取日期列表dateList
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        OrderReportVO orderReportVO = new OrderReportVO();
        orderReportVO.setDateList(StringUtils.join(dateList, ","));

        //获取每日订单数和有效订单数

        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;
        Double orderCompletionRate;

        for (LocalDate date : dateList) {
            //获取每日订单数
            Map map = new HashMap<>();
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            map.put("end", endTime);
            map.put("begin", beginTime);
            Integer orderCount = orderMapper.getOrderCount(map);
            orderCountList.add(orderCount);
            //获取订单总数
            totalOrderCount = totalOrderCount + orderCount;

            //获取每日有效订单数
            map.put("status", Orders.COMPLETED);
            Integer completeOrderCount = orderMapper.getOrderCount(map);
            validOrderCountList.add(completeOrderCount);
            //获取有效订单总数
            validOrderCount = validOrderCount + completeOrderCount;
        }
        orderReportVO.setOrderCountList(StringUtils.join(orderCountList, ","));
        orderReportVO.setValidOrderCountList(StringUtils.join(validOrderCountList, ","));
        orderReportVO.setTotalOrderCount(totalOrderCount);
        orderReportVO.setValidOrderCount(validOrderCount);

        //获取有效订单率
        orderCompletionRate = totalOrderCount > 0 ? ((double) validOrderCount / totalOrderCount) : null;
        orderReportVO.setOrderCompletionRate(orderCompletionRate);

        return orderReportVO;
    }


    /*
     *
     * 查询销量排名top10
     *
     * */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {

        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);

        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getOrderTop10(beginTime, endTime);
        List<String> nameList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();

        String nameTop10 = StringUtils.join(nameList, ",");

        String numberTop10 = StringUtils.join(numberList, ",");

        salesTop10ReportVO.setNameList(nameTop10);
        salesTop10ReportVO.setNumberList(numberTop10);

        return salesTop10ReportVO;
    }


    /*
     *
     * 导出运营数据表
     *
     * */
    @Override
    public void exportBusinessData(HttpServletResponse response) {

        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));

        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");


        try {
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);

            XSSFSheet sheet = excel.getSheet("Sheet1");

            sheet.getRow(1).getCell(1).setCellValue("时间:" + dateBegin + "至" + dateEnd);

            XSSFRow row = sheet.getRow(3);

            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            row = sheet.getRow(4);

            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());


            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }





            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }





    }
}
